package com.hospital.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hospital.common.core.domain.R;
import com.hospital.common.utils.StringUtils;
import com.hospital.common.core.page.TableDataInfo;
import com.hospital.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hospital.workstation.constant.DictConstants;
import com.hospital.workstation.domain.GradingTwo;
import com.hospital.workstation.domain.PatientBaseInfo;
import com.hospital.workstation.domain.vo.CareLevelTriggerItemVo;
import com.hospital.workstation.domain.vo.GradingTwoVo;
import com.hospital.workstation.mapper.GradingTwoMapper;
import com.hospital.workstation.mapper.PatientBaseInfoMapper;
import com.hospital.workstation.utils.CareLevelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.hospital.workstation.domain.bo.GradingFirstBo;
import com.hospital.workstation.domain.vo.GradingFirstVo;
import com.hospital.workstation.domain.GradingFirst;
import com.hospital.workstation.mapper.GradingFirstMapper;
import com.hospital.workstation.service.IGradingFirstService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 医学一级监护分级信息Service业务层处理
 *
 * @author whb
 * @date 2023-05-22
 */
@RequiredArgsConstructor
@Service
public class GradingFirstServiceImpl implements IGradingFirstService {

    private final GradingFirstMapper baseMapper;
    private final GradingTwoMapper gradingTwoMapper;
    private final PatientBaseInfoMapper patientBaseInfoMapper;

    /**
     * 查询医学一级监护分级信息
     */
    @Override
    public GradingFirstVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询医学一级监护分级信息列表
     */
    @Override
    public TableDataInfo<GradingFirstVo> queryPageList(GradingFirstBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GradingFirst> lqw = buildQueryWrapper(bo);
        Page<GradingFirstVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询医学一级监护分级信息列表
     */
    @Override
    public List<GradingFirstVo> queryList(GradingFirstBo bo) {
        LambdaQueryWrapper<GradingFirst> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GradingFirst> buildQueryWrapper(GradingFirstBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GradingFirst> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMedicalRecordNo() != null, GradingFirst::getMedicalRecordNo, bo.getMedicalRecordNo());
        lqw.eq(StringUtils.isNotBlank(bo.getItemOne()), GradingFirst::getItemOne, bo.getItemOne());
        lqw.eq(StringUtils.isNotBlank(bo.getItemTwo()), GradingFirst::getItemTwo, bo.getItemTwo());
        lqw.eq(StringUtils.isNotBlank(bo.getItemThree()), GradingFirst::getItemThree, bo.getItemThree());
        lqw.eq(StringUtils.isNotBlank(bo.getItemFour()), GradingFirst::getItemFour, bo.getItemFour());
        lqw.eq(StringUtils.isNotBlank(bo.getItemFive()), GradingFirst::getItemFive, bo.getItemFive());
        lqw.eq(StringUtils.isNotBlank(bo.getItemSix()), GradingFirst::getItemSix, bo.getItemSix());
        lqw.eq(StringUtils.isNotBlank(bo.getItemSeven()), GradingFirst::getItemSeven, bo.getItemSeven());
        lqw.eq(StringUtils.isNotBlank(bo.getItemEight()), GradingFirst::getItemEight, bo.getItemEight());
        lqw.eq(StringUtils.isNotBlank(bo.getItemNine()), GradingFirst::getItemNine, bo.getItemNine());
        lqw.eq(StringUtils.isNotBlank(bo.getItemTen()), GradingFirst::getItemTen, bo.getItemTen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemEleven()), GradingFirst::getItemEleven, bo.getItemEleven());
        lqw.eq(StringUtils.isNotBlank(bo.getItemTwelve()), GradingFirst::getItemTwelve, bo.getItemTwelve());
        lqw.eq(StringUtils.isNotBlank(bo.getItemThirteen()), GradingFirst::getItemThirteen, bo.getItemThirteen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemFourteen()), GradingFirst::getItemFourteen, bo.getItemFourteen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemFifteen()), GradingFirst::getItemFifteen, bo.getItemFifteen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemSixteen()), GradingFirst::getItemSixteen, bo.getItemSixteen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemSeventeen()), GradingFirst::getItemSeventeen, bo.getItemSeventeen());
        lqw.eq(StringUtils.isNotBlank(bo.getItemEighteen()), GradingFirst::getItemEighteen, bo.getItemEighteen());
        lqw.eq(StringUtils.isNotBlank(bo.getRenalFunction()), GradingFirst::getRenalFunction, bo.getRenalFunction());
        lqw.eq(StringUtils.isNotBlank(bo.getAltValue()), GradingFirst::getAltValue, bo.getAltValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAstValue()), GradingFirst::getAstValue, bo.getAstValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAlpValue()), GradingFirst::getAlpValue, bo.getAlpValue());
        lqw.eq(StringUtils.isNotBlank(bo.getTbil()), GradingFirst::getTbil, bo.getTbil());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecialAntibiosis()), GradingFirst::getSpecialAntibiosis, bo.getSpecialAntibiosis());
        lqw.eq(StringUtils.isNotBlank(bo.getHighWarningPills()), GradingFirst::getHighWarningPills, bo.getHighWarningPills());
        lqw.eq(StringUtils.isNotBlank(bo.getCareLevelValue()), GradingFirst::getCareLevelValue, bo.getCareLevelValue());
        return lqw;
    }

    /**
     * 新增医学一级监护分级信息
     */
    @Override
    public Boolean insertByBo(GradingFirstBo bo) {
        GradingFirst add = BeanUtil.toBean(bo, GradingFirst.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医学一级监护分级信息
     */
    @Override
    public Boolean updateByBo(GradingFirstBo bo) {
        GradingFirst update = BeanUtil.toBean(bo, GradingFirst.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GradingFirst entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除医学一级监护分级信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询药学一级监护分级信息
     *
     * @param medicalRecordNo 病历号
     * @return
     */
    @Override
    public GradingFirstVo queryByMedicalRecordNo(Integer medicalRecordNo) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<GradingFirst>().eq(GradingFirst::getMedicalRecordNo, medicalRecordNo));
    }

    /**
     * 更新一级分级信息和患者监护分级
     *
     * @param bo
     * @return
     */
    @Transactional
    @Override
    public Boolean insertOrUpdateByBo(GradingFirstBo bo) {
        try {
            // 更新一级监护分级信息
            GradingFirst gradingFirst = BeanUtil.toBean(bo, GradingFirst.class);
            baseMapper.updateById(gradingFirst);
            // 查询患者的基本信息
            PatientBaseInfo baseInfo = patientBaseInfoMapper.selectOne(new LambdaQueryWrapper<PatientBaseInfo>().eq(PatientBaseInfo::getMedicalRecordNo, gradingFirst.getMedicalRecordNo()));
            // 判断患者是否属于一级监护
            if (ObjectUtil.isNotNull(gradingFirst) && ObjectUtil.isNotNull(baseInfo)) {
                boolean isFirstGrading = CareLevelUtil.isFirstGrading(gradingFirst);
                if (isFirstGrading) { // 属于一级监护，更新患者监护分级
                    baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_THREE);
                    patientBaseInfoMapper.updateById(baseInfo);
                } else { // 不属于一级监护
                    // 查询药学二级监护信息
                    GradingTwo gradingTwo = gradingTwoMapper.selectOne(new LambdaQueryWrapper<GradingTwo>().eq(GradingTwo::getMedicalRecordNo, gradingFirst.getMedicalRecordNo()));
                    // 判断是否属于二级监护
                    boolean isTwoGrading = CareLevelUtil.isTwoGrading(gradingTwo);
                    if (isTwoGrading) { // 设置为二级
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_TWO);
                    } else { // 设置为三级
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_ONE);
                    }
                    // 更新患者药学监护分级
                    patientBaseInfoMapper.updateById(baseInfo);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查询标红项
     *
     * @param medicalRecordNo 病历号
     * @return
     */
    @Override
    public R<CareLevelTriggerItemVo> getRedItemVo(Integer medicalRecordNo) {
        try {
            // 创建药学监护信息触发项视图对象
            CareLevelTriggerItemVo careLevelTriggerItemVo = new CareLevelTriggerItemVo();
            // 查询一级监护分级信息
            GradingFirstVo gradingFirstVo = baseMapper.selectVoOne(new LambdaQueryWrapper<GradingFirst>().eq(GradingFirst::getMedicalRecordNo, medicalRecordNo));
            // 是否属于一级监护
            boolean isFirstGrading = CareLevelUtil.isFirstGrading(BeanUtil.toBean(gradingFirstVo, GradingFirst.class));
            if (isFirstGrading) {
                careLevelTriggerItemVo.setGradingFirstVo(gradingFirstVo);
                return R.ok("查询成功", careLevelTriggerItemVo);
            }
            // 查询二级监护分级信息
            GradingTwoVo gradingTwoVo = gradingTwoMapper.selectVoOne(new LambdaQueryWrapper<GradingTwo>().eq(GradingTwo::getMedicalRecordNo, medicalRecordNo));
            // 是否属于二级监护
            boolean isTwoGrading = CareLevelUtil.isTwoGrading(BeanUtil.toBean(gradingTwoVo, GradingTwo.class));
            if (isTwoGrading) {
                careLevelTriggerItemVo.setGradingTwoVo(gradingTwoVo);
                return R.ok("查询成功", careLevelTriggerItemVo);
            }
            return R.ok("查询成功", careLevelTriggerItemVo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询失败");
        }
    }
}
